package com.easy.common.util;
//从本地上传图片到阿里云oss

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ImageUtil {

    private static final String ENDPOINT="oss-cn-beijing.aliyuncs.com";
    private static final String BUCKET_NAME="qingyanxingfeng";
    private static final String ACCESS_KEY_ID="LTAI5tBK2D3X1kazEvkTvsPa";
    private static final String ACCESS_KEY_SECRET="ZLGQEp5x8IrChcUkYhbbEXQsXdRrmp";
    //创建OSSClient实例,用于和OSS服务进行交互
    private static final OSS ossClient=new OSSClientBuilder().build("http://"+ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
    //上传文件到oss
    public static String upload(InputStream is, String fileName) throws Exception{
        String newFileName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        //请求对象
        PutObjectRequest request=new PutObjectRequest(BUCKET_NAME,
                newFileName,is);
        //响应对象
        PutObjectResult result=ossClient.putObject(request);
        return "https://"+BUCKET_NAME+"."+ENDPOINT+"/"+newFileName;
    }
    //获取OSS存储空间中的文件列表
    public static List<String> getFileList(){//获取文件列表
        List<String> list=new ArrayList<>();
        ListObjectsRequest request=new ListObjectsRequest(BUCKET_NAME);//获取文件的请求
        request.setMarker(null);
        request.setMaxKeys(1000);
        ObjectListing objectListing=ossClient.listObjects(request);
        for(OSSObjectSummary objectSummary:objectListing.getObjectSummaries()){
            list.add(objectSummary.getKey());
        }
        return list;
    }
    //删除OSS中的单个文件
    public static void delete(String fileName) {
        ossClient.deleteObject(BUCKET_NAME, fileName);//删除文件
    }
    //批量删除OSS中的文件
    public static void deleteList(List<String> fileNameList){
        DeleteObjectsRequest deleteObjectsRequest=new DeleteObjectsRequest(BUCKET_NAME);
        deleteObjectsRequest.setKeys(fileNameList);
        ossClient.deleteObjects(deleteObjectsRequest);
    }
    //测试
    public static void main(String[] args) {
        System.out.println(getFileList());

        System.out.println(getFileList());
    }//主函数可能需删除20250824留
//        try {
//            MultipartFile mfile=null;
//            mfile.getInputStream();
//            File file=new File("D:\\javacode\\GameMallManagementSystem\\upload\\avatar\\cq.png");
//            InputStream is=new FileInputStream( file);
//            String newFileName=upload(is,file.getName());
//            System.out.println(newFileName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//    public static String upload(MultipartFile file) throws Exception{
//        return upload(file.getInputStream(),file.getOriginalFilename());
//    }

}
